#include "widget.h"
#include "ui_widget.h"
#include <QFileDialog>
#include <QDebug>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle(QString("Qt监听文件、文件夹变化 V%1").arg(APP_VERSION));


    connect(&m_watcher, &QFileSystemWatcher::fileChanged, this, &Widget::on_fileChanged);
    connect(&m_watcher, &QFileSystemWatcher::directoryChanged, this, &Widget::on_directoryChanged);
}

Widget::~Widget()
{
    delete ui;
}

/**
 * @brief  当指定路径下的文件被修改、重命名或从磁盘删除时触发。
 * @param path
 */
void Widget::on_fileChanged(const QString &path)
{
    ui->textEdit->append("文件更改：" + path);
}

/**
 * @brief 当指定路径下的目录被修改（例如，当文件被添加或删除时）或从磁盘中删除时触发。
 * @param path
 */
void Widget::on_directoryChanged(const QString &path)
{
    ui->textEdit->append("文件夹更改：" + path);
}

/**
 * @brief 添加监听文件
 */
void Widget::on_but_add_file_clicked()
{
    QString file = QFileDialog::getOpenFileName(this, "选择监听文件", "./", "文件(*)");
    if(!file.isEmpty())
    {
        bool ret = m_watcher.addPath(file);
        if(ret)
        {
            ui->textEdit->append("添加监听文件：" + file);
        }
        else
        {
            ui->textEdit->append("添加监听文件失败：" + file);
        }
    }
}

/**
 * @brief 添加监听路径
 */
void Widget::on_but_add_path_clicked()
{

    QString path = QFileDialog::getExistingDirectory(this, "选择监听路径",
                                                     "./",
                                                     QFileDialog::ShowDirsOnly
                                                   | QFileDialog::DontResolveSymlinks);
    if(!path.isEmpty())
    {
        bool ret = m_watcher.addPath(path);
        if(ret)
        {
            ui->textEdit->append("添加监听路径：" + path);
        }
        else
        {
            ui->textEdit->append("添加监听路径失败：" + path);
        }
    }
}


void Widget::on_but_remove_clicked()
{
    for(auto& file : m_watcher.files())
    {
        bool ret = m_watcher.removePath(file);
        if(ret)
        {
            ui->textEdit->append("移除监听文件：" + file);
        }
    }
    for(auto& dir : m_watcher.directories())
    {
        bool ret = m_watcher.removePath(dir);
        if(ret)
        {
            ui->textEdit->append("移除监听路径：" + dir);
        }
    }
}


void Widget::on_but_show_clicked()
{
    for(auto& file : m_watcher.files())
    {
        ui->textEdit->append(file);
    }
    for(auto& dir : m_watcher.directories())
    {
        ui->textEdit->append(dir);
    }
}

